package one.bugu.android.demon.util;

import android.os.CountDownTimer;

/**
 * 定时任务工具类
 */
public class TimerTaskUtils {

    /**
     * 定时器
     */
    private CountDownTimer countDownTimer;
    /**
     * 单例对象
     */
    private static volatile TimerTaskUtils singleton = null;

    private TimerTaskUtils() {

    }

    /**
     * 获取单例对象
     *
     * @return 单例对象
     */
    public static TimerTaskUtils getInstance() {
        if (singleton == null) {
            synchronized (TimerTaskUtils.class) {
                if (singleton == null) {
                    singleton = new TimerTaskUtils();
                }
            }
        }
        return singleton;
    }

    /**
     * 开启单次定时任务
     */
    public void startSingleTimerTask(final long timeIntervalS, final OnTimerTaskEvent onTimerTaskEvent) {
        startTimerTask(timeIntervalS, true, onTimerTaskEvent);
    }

    /**
     * 开启重复定时任务
     */
    public void startRepeatTimerTask(final long timeIntervalS, final OnTimerTaskEvent onTimerTaskEvent) {
        startTimerTask(timeIntervalS, false, onTimerTaskEvent);
    }

    /**
     * 开始定时任务
     *
     * @param timeIntervalS   定时任务时长, 单位秒
     * @param isSingTimerTask 是否为单次定时器
     */
    private void startTimerTask(final long timeIntervalS, final boolean isSingTimerTask, final OnTimerTaskEvent onTimerTaskEvent) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        countDownTimer = new CountDownTimer(timeIntervalS * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (onTimerTaskEvent != null) {
                    onTimerTaskEvent.onTickEvent(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                if (onTimerTaskEvent != null) {
                    onTimerTaskEvent.onFinishEvent();
                }
                if (!isSingTimerTask) {
                    startTimerTask(timeIntervalS, isSingTimerTask, onTimerTaskEvent);
                }
            }
        }.start();
    }

    /**
     * 结束定时器
     */
    public void endTimerTask() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    /**
     * 定时器事件监听
     */
    public interface OnTimerTaskEvent {
        /**
         * 定时器回调
         *
         * @param millisUntilFinished 进度
         */
        void onTickEvent(long millisUntilFinished);

        /**
         * 定时器完成回调
         */
        void onFinishEvent();
    }
}
